package cn.threewaters.qtyy.config.shiro;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import cn.threewaters.qtyy.dit.one.entity.SysUser;

public class EncryptPwd {
	/**
	 * 随机数
	 */
	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	/**
	 * 加密方式
	 */
	private String algorithmName = "md5";
	/**
	 * 散列次数(加密次数)
	 */
	private int hashIterations = 3;

	/**
	 * 为用户设置加密策略和盐值
	 * 
	 * @param user
	 *            用户
	 */
	public void encryptPassword(SysUser user) {
		user.setSalt(randomNumberGenerator.nextBytes().toHex());// 增加盐值
		/**
		 * 加密策略
		 */
		String newPassword = new SimpleHash(algorithmName, user.getPassword(),
				ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();
		user.setPassword(newPassword);
	}

	public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
		this.randomNumberGenerator = randomNumberGenerator;
	}

	public void setAlgorithmName(String algorithmName) {
		this.algorithmName = algorithmName;
	}

	public void setHashIterations(int hashIterations) {
		this.hashIterations = hashIterations;
	}

	public static void main(String[] args) {
		SysUser user = new SysUser();
		user.setUsername("admin");
		user.setPassword("123456");
		EncryptPwd p = new EncryptPwd();
		p.encryptPassword(user);
		System.out.println("salt=====" + user.getSalt() + "|||||password:" + user.getPassword());
	}
}
